package com.xxchat.utils;

//import com.maxmind.geoip2.DatabaseReader;
//import com.maxmind.geoip2.model.CityResponse;
import com.jthinking.common.util.ip.IPInfo;
import com.jthinking.common.util.ip.IPInfoUtils;
import com.xxchat.entity.dto.GeoInfoDTO;
import com.xxchat.entity.enums.ResponseCodeEnum;
import com.xxchat.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;

/**
 * @author Waicc
 */
public class IPAreaUtils {

    private static final Logger logger = LoggerFactory.getLogger(IPAreaUtils.class);

//    // 单例模式
//    private static DatabaseReader reader;
//
//    static {
//        try {
//            File database = new File("path/to/GeoLite2-City.mmdb");
//            reader = new DatabaseReader.Builder(database).build();
//        } catch (IOException e) {
//            throw new RuntimeException("Failed to load GeoIP database", e);
//        }
//    }

    public static String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");

        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        // 对于通过多个代理的情况，第一个IP为客户端真实IP
        if (ip != null && ip.contains(",")) {
            ip = ip.split(",")[0].trim();
        }

        return ip;
    }

    public static GeoInfoDTO getLocationInfo(String ip) {
        IPInfo ipInfo = IPInfoUtils.getIpInfo("112.3.47.50");
        GeoInfoDTO geoInfoDTO = new GeoInfoDTO();
        return geoInfoDTO.setIp(ip)
                .setCountry(ipInfo.getCountry())
                .setProvince(ipInfo.getProvince())
                .setAddress(ipInfo.getAddress())
                .setIsp(ipInfo.getIsp());
    }
}
